﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 订阅模式2
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建通知者
            ConcreteSubject s = new ConcreteSubject();
            //为通知者添加状态改变后要调用的观察者对象
            s.Attach(new A1(s, "X"));
            s.Attach(new A1(s, "Y"));
            s.Attach(new A1(s, "Z"));

            s.SubjectState = "ABC";
            //调用观察者的更改。
            s.Notify();
            Console.Read();

        }
    }


    abstract class Subject
    {
        private IList<Observer> observers = new List<Observer>();
        //增加观察者
        public void Attach(Observer observer)
        {
            observers.Add(observer);
        }
        //移除观察者
        public void Detach(Observer observer)
        {
            observers.Remove(observer);
        }
        //通知
        public void Notify()
        {
            foreach (Observer o in observers)
            {
                o.Update();
            }
        }



    }

    //通知者
    class ConcreteSubject : Subject
    {
        private string subjectState;

        //具体通知者状态
        public string SubjectState
        {
            get { return subjectState; }
            set { subjectState = value; }
        }


    }
    //观察者
    abstract class Observer
    {
        public abstract void Update();
    }

    class A1 : Observer
    {
        private string name;
        private string observerState;
        private ConcreteSubject subject;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sub">通知者</param>
        /// <param name="name">订阅者</param>
        public A1(ConcreteSubject sub,string name)
        {
            this.subject = sub;
            this.name = name;

        }

        public override void Update()
        {
            observerState = subject.SubjectState;
            Console.WriteLine("观察者{0}的新状态是{1}", name, observerState);
        }





    }





}
